package com.aat.dxfy.sync;

import java.io.*;
import java.util.*;
import java.util.Map.Entry;

public class SyncFilesTest01 {
	public static List<Map<String,Long>> lists=new ArrayList<Map<String,Long>>();
	public static void main(String[] args) throws IOException {
		String dirA="/Users/dxy/Desktop/a";
		String dirB="/Users/dxy/Desktop/b";
		
		//正向
		chkFiles(dirA);
		doSync(dirA, dirB);
		
		//反向
		lists.clear();
		chkFiles(dirB);
		doSync(dirB, dirA);
	}
	
	public static void doSync(String dirA,String dirB) throws IOException{
		for (Map<String,Long> map : lists) {
			Set<Entry<String,Long>> set= map.entrySet();
			String apath = set.iterator().next().getKey();
			Long aTime = set.iterator().next().getValue();
			String aFilePath=apath.substring(apath.indexOf(dirA)+dirA.length(), apath.length());
			String bFilePath=dirB+aFilePath;
			File bFile=new File(bFilePath);
			if(bFile.exists()){
				Long bTime=bFile.lastModified();
				if(aTime>bTime){
					//A->B
					copyFileAtoB(apath, bFilePath);
				}else{
					//B->A
					copyFileAtoB(bFilePath, apath);
				}
			}else{
				//A->B
				copyFileAtoB(apath, bFilePath);
			}
		}
	}

	//列出文件
	public static void chkFiles(String dirA){
		File filesA=new File(dirA);
		File[] files = filesA.listFiles();
		for (File file : files) {
			if(file.isDirectory()){
				chkFiles(file.getAbsolutePath());
			}else{
				String filePath=file.getAbsolutePath();
				Long fileTime=file.lastModified();
				Map<String,Long> map=new HashMap<String,Long>();
				map.put(filePath, fileTime);
				lists.add(map);
			}
		}
	}
	
	//进行拷贝
	public static void copyFileAtoB(String fileA,String fileB) throws IOException{
		File file=new File(fileB);
		if(!file.exists()){
			String fileP =file.getParent();
			File f=new File(fileP);
			f.mkdirs();
		}
		InputStream in=new FileInputStream(fileA);
		OutputStream out=new FileOutputStream(fileB);
		byte[] bs=new byte[102400];
		int i=-1;
		while((i=in.read(bs))>0){
			out.write(bs, 0, i);
		}
		out.flush();
		in.close();
		out.close();
	}

}

/**
 String ss[] = fileB.split(File.separator);
			String fileNew="";
			if(ss[0]==null||"".equals(ss[0])||ss[0].length()==0){
				fileNew=File.separator;
			}else{
				fileNew=ss[0];
			}
			for (int i = 1; i < ss.length-1; i++) {
				fileNew+=ss[i]+File.separator;
				File f=new File(fileNew);
				if(!f.exists()){
					f.mkdirs();
				}
			}
 */
